package com.hk.manager.upload;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.hk.config.CosConfig;
import com.hk.exception.BusinessException;
import com.hk.exception.ErrorCode;
import com.hk.manager.CosManager;
import com.hk.model.vo.file.UploadFileVO;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 文件上传处理器
 *
 * @author huangkun
 * @date 2024/12/25 20:01
 */
@Slf4j
public abstract class UploadHandler<T> {
    @Resource
    private CosConfig config;
    @Resource
    private CosManager cosManager;

    private static final String FILE_SUFFIX = "png";

    public UploadFileVO upload(T inputSource, String filePrefix) {
        //校验文件是否合法
        validateFile(inputSource);
        //获取文件原始名称
        String originalFileName = getOriginalFileName(inputSource);
        //获取文件后缀名
        String fileSuffix = FileUtil.getSuffix(originalFileName);
        if (StrUtil.isBlank(fileSuffix)){
            fileSuffix = FILE_SUFFIX;
        }
        //上传文件
        String uuid = RandomUtil.randomString(16);
        String fileName = String.format("%s_%s.%s", DateUtil.format(new Date(), "yyyyMMddHHmmss"), uuid, fileSuffix);
        String filePath = String.format("/%s/%s", filePrefix, fileName);
        File tempFile = null;
        try {
            //创建临时文件
            tempFile = File.createTempFile(filePath, null);
            //处理文件
            handleFile(inputSource, tempFile);
            //上传文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (CollectionUtil.isNotEmpty(objectList)) {
                //返回压缩格式
                CIObject compressedCiObject = objectList.get(0);
                return buildUploadFileVO(originalFileName, compressedCiObject,filePath,imageInfo);
            }
            return buildUploadFileVO(imageInfo, originalFileName, tempFile, filePath);
        } catch (IOException e) {
            log.error("上传失败", e);
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "上传失败");
        } finally {
            if (tempFile != null) {
                //删临时文件
                tempFile.delete();
            }
        }

    }



    protected abstract void handleFile(T inputSource, File tempFile);

    protected abstract String getOriginalFileName(T inputSource);

    protected abstract void validateFile(T inputSource);

    private UploadFileVO buildUploadFileVO(String originalFileName, CIObject compressedCiObject, String filePath, ImageInfo imageInfo) {
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setPicFormat(compressedCiObject.getFormat());
        uploadFileVO.setFileName(originalFileName);
        uploadFileVO.setFileSize(compressedCiObject.getSize().longValue());
        uploadFileVO.setUrl(config.getHost() + filePath);
        uploadFileVO.setAddress(filePath);
        int width = compressedCiObject.getWidth();
        uploadFileVO.setPicWidth(width);
        int height = compressedCiObject.getHeight();
        uploadFileVO.setPicHeight(height);
        double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        uploadFileVO.setPicScale(picScale);
        uploadFileVO.setPicColor(imageInfo.getAve());
        return uploadFileVO;
    }

    private UploadFileVO buildUploadFileVO(ImageInfo imageInfo, String originalFileName, File tempFile, String filePath) {
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setPicFormat(imageInfo.getFormat());
        uploadFileVO.setFileName(originalFileName);
        uploadFileVO.setFileSize(FileUtil.size(tempFile));
        uploadFileVO.setUrl(config.getHost() + filePath);
        uploadFileVO.setAddress(filePath);
        int width = imageInfo.getWidth();
        uploadFileVO.setPicWidth(width);
        int height = imageInfo.getHeight();
        uploadFileVO.setPicHeight(height);
        double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        uploadFileVO.setPicScale(picScale);
        uploadFileVO.setPicColor(imageInfo.getAve());
        return uploadFileVO;
    }
}
